"""
视图函数

"""

from flask import current_app, session, request, jsonify
from flask import render_template

from info import constants
from info.models import User, Category, News
from info.modules.index import index_blu
from info.utils.response_code import RET


@index_blu.route("/")
def index():

    # 判断用户是否登陆 因为HTTP协议是无状态的，为了保持有状态，就通过cookie和session来判断
    # 根据本地的session来判断 获取用户ID
    # user_id = session["user_id"]
    user_id = session.get("user_id")
    # 先声明user为NONE
    user = None
    if user_id:
        try:
            user = User.query.get(user_id)
        except Exception as e:
            current_app.logger.error(e)

    # # 完成导航栏部分的分类信息
    # # 导航栏的分类信息是从数据库中查询分类表中的数据,然后用模板渲染出来
    category_list = None
    try:
        category_list = Category.query.all()
    except Exception as e:
        current_app.logger.debug(e)

    # 完成右侧的热搜信息
    # 按照点击排行获取前10条信息
    hot_news = None
    try:
        hot_news = News.query.order_by(News.clicks.desc()).limit(constants.CLICK_RANK_MAX_NEWS)
    except Exception as e:
        current_app.logger.error(e)

    click_news_list = []
    for news in hot_news:
        click_news_list.append(news.to_basic_dict())

    # 测试session
    # session["age"] = 1111
    # 存储在redis数据库的格式： "session:4e696341-3a6b-4a9f-9c95-d9660f54915e"
    # 通过get key session:4e696341-3a6b-4a9f-9c95-d9660f54915e 得到的结果是\x80\x03}q\x00X\x03\x00\x00\x00ageq\x01MW\x04s.
    # 造成这样的原因是，session的存储本身是加密的。
    current_app.logger.debug('debug')
    # return "这是一个首页测试session2"
    # 把用户的信息返回过去
    return render_template("news/index2.html", user=user, click_news_list=click_news_list,category_list=category_list)


# 加载/favicon.ico并返回静态文件
@index_blu.route("/favicon.ico")
def get_favicon():
    # 通过调用send_static_file方法返回
    return current_app.send_static_file("news/favicon.ico")


# @index_blu.route('/newslist')
# def get_news_list():
#     """
#     获取指定分类的新闻列表
#     1. 获取参数
#     2. 校验参数
#     3. 查询数据
#     4. 返回数据
#     :return:
#     """
#
#     # 1. 获取参数
#     args_dict = request.args
#     page = args_dict.get("p", '1')
#     per_page = args_dict.get("per_page", constants.HOME_PAGE_MAX_NEWS)
#     category_id = args_dict.get("cid", '1')
#
#     # 2. 校验参数
#     try:
#         page = int(page)
#         per_page = int(per_page)
#     except Exception as e:
#         current_app.logger.error(e)
#         return jsonify(errno=RET.PARAMERR, errmsg="参数错误")
#
#     # 3. 查询数据并分页
#     filters = []
#     # 如果分类id不为1，那么添加分类id的过滤
#     if category_id != "1":
#         filters.append(News.category_id == category_id)
#     try:
#         paginate = News.query.filter(*filters).order_by(News.create_time.desc()).paginate(page, per_page, False)
#         # 获取查询出来的数据
#         items = paginate.items
#         # 获取到总页数
#         total_page = paginate.pages
#         current_page = paginate.page
#     except Exception as e:
#         current_app.logger.error(e)
#         return jsonify(errno=RET.DBERR, errmsg="数据查询失败")
#
#     news_li = []
#     for news in items:
#         news_li.append(news.to_basic_dict())
#
#     # 4. 返回数据
#     return jsonify(errno=RET.OK, errmsg="OK", totalPage=total_page, currentPage=current_page, newsList=news_li, cid=category_id)


# 完成新闻列表页的逻辑
@index_blu.route("/news_list")
def news_list():

    """
    完成新闻列表逻辑
    :param: cid 分类ID　String
    :param: currentPage 页数，不传默认获取为1　int
    :param: per_page 每页显示多少条数据，如果不传，默认10条　String

    :return: json
        {
            errno                       int    是    错误码
            errmsg	                    string	是	错误信息
            cid	                        string	是	当前新闻数据的分类id
            totalPage	                int	    否	总页数
            currentPage	                int	    否	当前页数
            newsList	                list	否	新闻列表数据
            newsList.title	            string	是	新闻标题
            newsList.source	            string	是	新闻来源
            newsList.digest	            string	是	新闻摘要
            newsList.create_time	    string	是	新闻时间
            newsList.index_image_url	string	是	新闻索引图
        }

    """
    # 1 从浏览器获取相关参数
    news_list_params = request.args

    cid = news_list_params.get("cid", 1)  # 如果获取不到，默认为1
    # "/news_list?cid='+currentCid+'&cur_page='+cur_page+'&per_page='+10+'"
    currentPage = news_list_params.get("cur_page")
    per_page = news_list_params.get("per_page", constants.HOME_PAGE_MAX_NEWS)

    try:
        cid = int(cid)
        currentPage = int(currentPage)
        per_page = int(per_page)
    except Exception as e:
        current_app.logger.debug(e)
        return jsonify(errno=RET.PARAMERR, errmsg="请求参数错误")

    # 2 根据用户请求的参数查询相关的结果
    # 查询对应分类中的信息
    news_list = []
    paginate = None
    # 因为最新不是消息的分类，而是按照点击排名的消息。因此需要对此进行判断
    if cid == 1:
        # 查询最新的10条信息
        paginate = News.query.order_by(News.create_time.desc()).paginate(currentPage, per_page, False)
        # result_news = db.session.query(News).order_by(News.create_time.desc()).paginate(currentPage, per_page, False)
    else:
        paginate = News.query.filter(News.category_id == cid).order_by(News.create_time.desc()).paginate(currentPage, per_page, False)
        # result_news = News.query.filter_by(category_id=cid).order_by(News.create_time.desc()).paginate(currentPage, per_page, False)

    # paginate 是一个对象 需要通过这个对象把当前页和总页数返回
    totalPage = paginate.pages
    currentPage = paginate.page

    # 获取查询出来的数据
    news_items = paginate.items
    """
    class Pagination(object):
    Internal helper class returned by :meth:`BaseQuery.paginate`.  You
    can also construct it from any other SQLAlchemy query object if you are
    working with other libraries.  Additionally it is possible to pass `None`
    as query object in which case the :meth:`prev` and :meth:`next` will
    no longer work.
    

    def __init__(self, query, page, per_page, total, items):
        #: the unlimited query object that was used to create this
        #: pagination object.
        self.query = query
        #: the current page number (1 indexed)
        self.page = page
        #: the number of items to be displayed on a page.
        self.per_page = per_page
        #: the total number of items matching the query
        self.total = total
        #: the items for the current page
        self.items = items

    
    """
    # 3  返回参数
    # print(result_news, type(result_news))

    # 上面的执行结果<flask_sqlalchemy.Pagination object at 0x000001F86F4CB4A8> <class 'flask_sqlalchemy.Pagination'>

    for news in news_items:
        # 过滤新闻状态
        if news.status == 0:
            news_list.append(news.to_basic_dict())

    return jsonify(errno=RET.OK,errmsg="查询成功",currentPage=currentPage,totalPage=totalPage,news_list=news_list,cid=cid)


